<?php
namespace app\user\controller;

use app\common\controller\Api;
use app\user\model\MemberModel;


class Login extends Api
{
    protected $noNeedLogin = '*';

    public function login()
    {
        $code = input('code');
//        $appId = 'wx3344dd253dbeabac';
//        $secret = '709553d3c74997f7fc36d08a06449a67';
        $appId = input('appid');
        $secret = input('secret');
        if (empty($code || empty($appId) || empty($secret))) {
            $this->error('参数不能为空');
        }
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$secret&js_code=$code&grant_type=authorization_code";
        $result = curlRequest('GET', $url, 'json');
//        halt($result);
        if (isset($result['errcode']) && $result['errcode'] != 0) {
            $this->error($result['errmsg']);
        }
        //根据 openid 查询是否已经存在了
        $model = new MemberModel();
        $user = $model->where('openid', $result['openid'])->find();
        if ($user) {
            $user->session_key = $result['session_key'];
            $user->last_login_time = date('Y-m-d H:i:s');
            if ($user->save()) {
                $this->success('登录成功', [
                    'token' => singToken($user['id'], 123)
                ]);
            } else {
                $this->error('登录失败', [
                    'token' => ' '
                ]);
            }
        } else {
            $model->openid = $result['openid'];
            $model->session_key = $result['session_key'];
            $model->create_time = date('Y-m-d H:i:s');
            if ($model->save()) {
                $user = $model->where('openid', $result['openid'])->find();
                $this->success('登录成功', [
                    'token' => singToken($user['id'], 123)
                ]);
            } else {
                $this->error('登录失败', [
                    'token' => ''
                ]);
            }

        }
    }
}